
const accessTokenKey = 'accessToken';
const refreshTokenKey = 'refreshToken';

const cache = type => ({
    set(key, value) {
        window[`${type}Storage`].setItem(key, JSON.stringify(value));
    },
    get(key) {
        let value = window[`${type}Storage`].getItem(key);
        try {
            value = JSON.parse(value);
        } catch (error) {
            console.warn(error);
        }
        return value;
    },
    remove(key) {
        window[`${type}Storage`].removeItem(key);
    },
});

const createTreeByList = (arr, pId = '0', idKey = 'id', pIdKey = 'parentId') => {
    const parentList = arr.filter(d => String(d[pIdKey]) === String(pId));
    return parentList.map(d => ({ ...d, children: createTreeByList(arr, d[idKey]) }));
};

const tools = {
    // 格式化URL，将带参url解析成path和参数对象
    parseURL(url) {
        const [path = '', queryString = ''] = (url || '').split('?');
        const query = {};
        (queryString.split('?')[0]).split('&').forEach(key => {
            const [k, v] = key.split('=');
            // 做兼容，有的时候路由路径出现问题，类似 /system/use?a=1&b=2#/index
            if (k) query[k] = (v || '').split('#/')[0];
        });
        return { path, query };
    },
    /**
     * 将字符串修改为驼峰命名，处理的符号包含短横线、下划线与空格；例如 'abc efg-da_mn' => 'abcEfgDaMn'
     * @param {String} str 需要处理的字符串
     * @param {Boolean} upperCaseFirst 首字母是否大写
     * @returns String
     */
    toCamelCase(str, upperCaseFirst) {
        str = (str || '').replace(/[-_\s]+(.)?/g, (_, c) => c ? c.toUpperCase() : '').replace(/\s+/g, '');
        if (str) str = `${upperCaseFirst ? str.charAt(0).toUpperCase() : str.charAt(0).toLowerCase()}${str.slice(1)}`;
        return str;
    },
    // 将列表数据依据id关联关系转成树形结构
    createTreeByList,
    /**
     * sessionCache.set(key, value)
     * 将value存到sessionStorage里，value可以是任何类型值（无需用JSON.stringify处理）
     * 
     * sessionCache.get(key)
     * 从sessionStorage里取值，值的类型为初始存入时的类型
     */
    sessionCache: cache('session'),
    localCache: cache('local'),
    setToken(token) {
        cache('local').set(accessTokenKey, token);
    },
    getToken() {
        return cache('local').get(accessTokenKey);
    },
    removeToken() {
        cache('local').remove(accessTokenKey);
    },
    setRefreshToken(token) {
        cache('local').set(refreshTokenKey, token);
    },
    getRefreshToken() {
        return cache('local').get(refreshTokenKey);
    },
    removeRefreshToken() {
        cache('local').remove(refreshTokenKey);
    },
};

export default tools;